package com.pengxun.manager.service.system.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.pengxun.common.config.constant.LoginConfig;
import com.pengxun.common.utils.ShiroSaltUtils;
import com.pengxun.manager.dao.system.UserinfoDao;
import com.pengxun.manager.model.system.UserRole;
import com.pengxun.manager.model.system.Userinfo;
import com.pengxun.manager.service.system.LoginService;
import com.pengxun.manager.service.system.UserRoleService;
import com.pengxun.manager.vo.CurrentUserVO;
import com.pengxun.manager.vo.LoginVO;
import com.szeastroc.common.constant.ErrorCode;
import com.szeastroc.common.exception.EastrocException;
import com.szeastroc.common.utils.ValidationUtils;

import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

@Service
public class LoginServiceImpl implements LoginService {

	@Resource
	private UserinfoDao userInfoDao;

	@Resource
	private UserRoleService userRoleService;


	@Resource
	private LoginConfig loginConfig;

	
	@Resource
	private HttpServletRequest request;

	/**
	 * 不允许变更
	 */
	public static final byte[] KEY_SECRET = "eyJleHAiOjE1NTEzNTIxOTcsInN1YiI6Ijg0NzlhZjk3YzdiMDRlMjVhYjgyNzNjNTA4NmUxYTEzIn0"
			.getBytes();

	@Override
	public String login(LoginVO loginVO) {

		ValidationUtils.validate(loginVO);

		Userinfo userinfo = userInfoDao.findByAccount(loginVO.getAccount().trim());

		if (userinfo == null) {
			throw new EastrocException("用户或密码错误");
		}

		String password = ShiroSaltUtils.generatePassword(loginVO.getPassword().trim(), userinfo.getSalt());
		if (!StringUtils.equals(password, userinfo.getPassword())) {
			throw new EastrocException("用户或密码错误");
		}

		String serviceToken = JSON.toJSONString(userinfo);

		DateTime dateTime = DateTime.now().plusHours(loginConfig.getTime());
		SecretKey key = Keys.hmacShaKeyFor(KEY_SECRET);
		String token = Jwts.builder().setExpiration(dateTime.toDate()).setSubject(serviceToken).signWith(key).compact();
		return token;
	}


	@Override
	public Userinfo getCurrentUser() {
		String token = request.getHeader("authorization");
		SecretKey key = Keys.hmacShaKeyFor(KEY_SECRET);
		String serviceToken = "";
		try {
			serviceToken = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
		} catch (ExpiredJwtException e) {
			throw new EastrocException("token is expired");
		} catch (Exception e) {
			throw new EastrocException("invalid token");
		}


		return JSON.parseObject(serviceToken, Userinfo.class);
	}

	@Override
	public CurrentUserVO getCurrentUserVO() {
		CurrentUserVO currentUserVO = new CurrentUserVO();
		Userinfo userinfo = getCurrentUser();
		BeanUtils.copyProperties(userinfo, currentUserVO);

		List<UserRole> userRoles = userRoleService.findByUserId(currentUserVO.getUserId());

		List<String> roles = new ArrayList<String>();
		if (!CollectionUtils.isEmpty(userRoles)) {
			for (UserRole userRole : userRoles) {
				roles.add(userRole.getRoleCode());
			}
			currentUserVO.setRoles(roles);
		}

		return currentUserVO;
	}

	/**
	 * 获取当前登录人的openId
	 * 
	 * @return 当前用户的openId
	 */
	public String getCurrentLoginUser() {
		String token = request.getHeader("authorization");

		if (StringUtils.isEmpty(token)) {
			throw new EastrocException(ErrorCode.NO_LOGIN.getCode(), "没有登录");
		}
		String openId = null;
		try {
			SecretKey key = Keys.hmacShaKeyFor(KEY_SECRET);
			openId = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
		}
		if (openId == null) {
			throw new EastrocException(ErrorCode.NO_LOGIN.getCode(), "没有登录");
		}

		return openId;
	}

}
